//
//  CGQShebeiListViewController.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/4/7.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView

class CGQShebeiListViewController: SYBaseTableViewController {
    
    fileprivate var vm: VGTableViewPageViewModel<NSshebeiRecordsModel>!
    
    var params: [String: String]?
    var topView: CGQshebeiTopView!
    var errorView = SYErrorView()
    var classType: String?
    var arryData: [NSshebeiRecordsModel]!
    var model: NSRecordsModel!
    
    init(model: NSRecordsModel) {
        super.init(nibName: nil, bundle: nil)
        self.model = model
        self.params = ["appId": model.id ?? ""]

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        setNoDataView()
        setupViewModel()
        self.title = "设备列表"
        setRightNavItem()
        classType = "quanbu"
        
        
        
    }
    
    func setRightNavItem() {
        let item: UIBarButtonItem = UIBarButtonItem(title: "新建", style: UIBarButtonItem.Style.plain, target: self, action: #selector(rightAction))
        self.navigationItem.rightBarButtonItem=item
    }
    
    @objc func rightAction() {
        let vc = CGQxinjianshebeiViewController(type: "新建")
        
        self.sy_push(vc)
    }
    
    
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<NSshebeiRecordsModel>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        
        
        vm.getList(type: .shebeiList(dic: self.params ?? [:], page: vm.vg_pageNo, size:10000), dispose: dispose)
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.vm.getList(type: .shebeiList(dic: self.params ?? [:], page: self.vm.vg_pageNo, size:10000), dispose: self.dispose)
                
            }
        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
        }
    }
    
    func setTableView() {
        
        topView = CGQshebeiTopView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 95.autoWidth()))
        topView.tixianBt .addTarget(self, action: #selector(SelectObj), for: .touchUpInside)
        topView.shanchu.addTarget(self, action: #selector(DelectObj), for: .touchUpInside)
        //        self.tableView.tableHeaderView = topView
        topView.quanbuBt.addTarget(self, action: #selector(classBtn), for: .touchUpInside)
        topView.lixianBt.addTarget(self, action: #selector(classBtn), for: .touchUpInside)
        topView.zaixianBt.addTarget(self, action: #selector(classBtn), for: .touchUpInside)
        self.topView.tf.text = self.model.appName

        topView.tf.rx.controlEvent(.editingDidEnd).subscribe(onNext: {
            [weak self] (_) in
            if let `self` = self {
                self.params = ["appName" : self.topView.tf.text ?? ""]

                self.setupViewModel()
            }
        }).disposed(by: dispose)

        
        self.view.addSubview(topView)
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: topView.frame.size.height+NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-BOTTOM_SAFE_HEIGHT-100.autoWidth()), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = Constant.bgViewColor
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    let v = self.vm.dataSource[indexPath.row]
                    
                    let vc = CGQshebeiInfoVC(id: v.id ?? "")
                    self.sy_push(vc)
                }
            })
            .disposed(by:dispose)
        
        errorView.isHidden = true
        errorView.frame = CGRect(x: 0.0, y: 0.0, width: SCREEN_WIDTH, height: self.view.frame.size.height)

        self.tableView.addSubview(errorView)
    }
    
    @objc func SelectObj(button: UIButton) {
        
        let selectVC = CGQxiangmuChoiceListViewController()
        selectVC.passParamsClosure = {[weak self] value in
            if let `self` = self {
                let v:NSRecordsModel = value as! NSRecordsModel
                self.params = ["appId": v.id ?? ""]
                self.topView?.tf.text = v.appName
                self .setupViewModel()
            }
        }
        self.pushVC(selectVC)
        
    }
    
    @objc func DelectObj(button: UIButton) {
        
        self.params = ["":""]
        self.topView?.tf.text = ""
        self .setupViewModel()
        
        
    }
    @objc func classBtn(button: UIButton) {
        
        if (button.tag == 1001)  {
            
            self.classType = "全部"
            self.topView.quanbuBt.isSelected = true
            self.topView.zaixianBt.isSelected = false
            self.topView.lixianBt.isSelected = false
            self.topView.tipLine.snp.remakeConstraints { (make) in
                make.top.equalToSuperview().offset(93.autoWidth())
                make.centerX.equalTo(self.topView.quanbuBt)
                make.width.equalTo(60.autoWidth())
                make.height.equalTo(1.5.autoWidth())
                
            }
            
        }
        else if(button.tag == 1002){
            self.classType = "在线"
            self.topView.quanbuBt.isSelected = false
            self.topView.zaixianBt.isSelected = true
            self.topView.lixianBt.isSelected = false
            self.topView.tipLine.snp.remakeConstraints { (make) in
                make.top.equalToSuperview().offset(93.autoWidth())
                make.centerX.equalTo(self.topView.zaixianBt)
                make.width.equalTo(60.autoWidth())
                make.height.equalTo(1.5.autoWidth())
                
            }
            
        }else if (button.tag == 1003){
            self.classType = "离线"
            self.topView.quanbuBt.isSelected = false
            self.topView.zaixianBt.isSelected = false
            self.topView.lixianBt.isSelected = true
            self.topView.tipLine.snp.remakeConstraints { (make) in
                make.top.equalToSuperview().offset(93.autoWidth())
                make.centerX.equalTo(self.topView.lixianBt)
                make.width.equalTo(60.autoWidth())
                make.height.equalTo(1.5.autoWidth())
                
            }
            
            
        }
        
        self.setupViewModel()
        
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        
        let title = String(format: "全部(%ld)",self.vm.dataSource.count)
        topView.quanbuBt.setTitle(title, for: .normal)
        let zaixian = self.vm.dataSource.filter { $0.isOnline == 1 }
        let lixian = self.vm.dataSource.filter { $0.isOnline == 0 }
        
        let zai = String(format: "在线(%ld)",zaixian.count)
        let li = String(format: "离线(%ld)",lixian.count)
        arryData = self.vm.dataSource
        if (self.classType == "在线"){
            
            arryData = zaixian
            
        }else if (self.classType == "离线"){
            
            arryData = lixian
        }
        
        if arryData.count == 0 {
            
            errorView.isHidden = false
        }else{
            errorView.isHidden = true
        }
        topView.zaixianBt.setTitle(zai , for: .normal)
        topView.lixianBt.setTitle(li , for: .normal)
        
        let sections = Observable.just([
            NSshebeiRecordsModelSection(header: "", items: arryData)//self.vm.dataSource)
        ])
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<NSshebeiRecordsModelSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                let cell: CGQshebeiCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? CGQshebeiCell ?? CGQshebeiCell(style: .default, reuseIdentifier: "Cell")
                cell.configureView(model: item)
                cell.passParamsClosure = {[weak self] value in
                    if let `self` = self {
                        
                        let v = value as! String
                        
                        
                        if v == "duankou" {
                            
                            print("v" + v)
                            
                            let model = item
                            let VC = CGQdetailViewController(id: model.id ?? "")
                            self.pushVC(VC)
                            
                        }
                        else if v == "mingcheng"{
                            
                        }
                        
                    }
                }
                cell.selectionStyle = .none
                return cell
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    
}


//自定义Section
struct NSshebeiRecordsModelSection {
    var header: String
    var items: [Item]
}

extension NSshebeiRecordsModelSection : AnimatableSectionModelType {
    typealias Item = NSshebeiRecordsModel
    
    var identity: String {
        return header
    }
    
    init(original: NSshebeiRecordsModelSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension NSshebeiRecordsModel: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}



class CGQshebeiTopView: SYBaseView {
    
    public var clickChoiceClosure: ((Int) -> Void)?
    
    
    fileprivate var bgView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = UIColor(hex: 0xF2F2F2)
        v.layer.cornerRadius = 17.5.autoWidth()
        return v
    }()
    
    public lazy var search: VGImageButton = {
        
        let v: VGImageButton = VGImageButton()
        v.imageView.image = UIImage(named: "sousuo")
        return v
    }()
    
    
    let tf: UITextField = {
        let v: UITextField = UITextField()
        v.font = 13.autoFontSize()
        v.placeholder = "选择项目"
//        v.isEnabled = false
        return v
    }()
    
    var shanchu: UIButton = {
        let v = UIButton()
        v.setTitleColor(UIColor.white, for: .normal)
        v.titleLabel?.font = 13.autoFontSize()
        v.setBackgroundImage(UIImage(named: "shanchu_icon"), for: .normal)
        
        return v
        
    }()
    
    var tixianBt: UIButton = {
        let v = UIButton()
        v.setTitle("选择项目", for: .normal)
        v.setTitleColor(UIColor.white, for: .normal)
        v.titleLabel?.font = 13.autoFontSize()
        v.setBackgroundImage(UIImage(named: "shebei_choice"), for: .normal)
        return v
    }()
    
    var quanbuBt: UIButton = {
        let v = UIButton()
        v.setTitle("全部(199)", for: .normal)
        v.setTitleColor(UIColor(hex: 0x333333), for: .selected)
        v.setTitleColor(UIColor(hex: 0x999999), for: .normal)
        v.isSelected = true
        v.titleLabel?.font = 14.autoFontSize()
        v.tag = 1001
        return v
    }()
    
    var zaixianBt: UIButton = {
        let v = UIButton()
        v.setTitle("在线(123)", for: .normal)
        v.setTitleColor(UIColor(hex: 0x333333), for: .selected)
        v.setTitleColor(UIColor(hex: 0x999999), for: .normal)
        v.titleLabel?.font = 14.autoFontSize()
        v.tag = 1002
        return v
    }()
    
    //    var kongxianBt: UIButton = {
    //        let v = UIButton()
    //        v.setTitle("空闲(20)", for: .normal)
    //        v.setTitleColor(UIColor(hex: 0x999999), for: .normal)
    //        v.titleLabel?.font = 14.autoFontSize()
    //        v.isHidden = true
    //        return v
    //    }()
    
    var lixianBt: UIButton = {
        let v = UIButton()
        v.setTitle("离线(56)", for: .normal)
        v.setTitleColor(UIColor(hex: 0x333333), for: .selected)
        v.setTitleColor(UIColor(hex: 0x999999), for: .normal)
        v.titleLabel?.font = 14.autoFontSize()
        v.tag = 1003
        return v
    }()
    
    var tipLine: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0x0782FF)
        return v
    }()
    
    override func initViews() {
        
        self.backgroundColor = .white
        //当文本框内容改变时，将内容输出到控制台上
        tf.rx.text.orEmpty.asObservable()
            .subscribe(onNext: {
                print("您输入的是：\($0)")
                if self.tf.text?.length == 0 {
                    //                    self.shanchu.isHidden = true
                    
                    
                    
                }
                
            })
            .disposed(by: disposeBag)
        //按下 return 键
        //        tf.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: {
        //            [weak self] (_) in
        //            if let `self` = self {
        //                if let c = self.clickChoiceClosure {
        //                    c(1)
        //                }
        //            }
        //        }).disposed(by: disposeBag)
        // 编辑完成
        tf.rx.controlEvent(.editingDidEnd).subscribe(onNext: {
            [weak self] (_) in
            if let `self` = self {
                if let c = self.clickChoiceClosure {
                    c(1)
                }
            }
        }).disposed(by: disposeBag)
        
        
        addSubview(bgView)
        bgView.addSubview(search)
        bgView.addSubview(tf)
        addSubview(shanchu)
        addSubview(tixianBt)
        addSubview(quanbuBt)
        addSubview(zaixianBt)
        addSubview(lixianBt)
        //        addSubview(kongxianBt)
        addSubview(tipLine)
        let itemWidth = SCREEN_WIDTH / 3
        bgView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(15.autoWidth())
            make.left.equalToSuperview().offset(10.autoWidth())
            make.right.equalToSuperview().offset(-68.0.autoWidth())
            make.height.equalTo(35.autoWidth())
        }
        search.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.width.height.equalTo(14.0.autoWidth())
            make.left.equalToSuperview().offset(14.autoWidth())
        }
        
        
        
        tixianBt.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(15.autoWidth())
            make.width.equalTo(75.autoWidth())
            make.height.equalTo(35.autoWidth())
            make.right.equalToSuperview().offset(-10.0.autoWidth())
        }
        shanchu.snp.makeConstraints { (make) in
            make.width.equalTo(14.autoWidth())
            make.height.equalTo(14.autoWidth())
            make.centerY.equalTo(tixianBt.snp.centerY)
            make.right.equalTo(tixianBt.snp.left).offset(-5.0.autoWidth())
        }
        tf.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(33.0.autoWidth())
            make.right.equalTo(shanchu.snp.left).offset(-10.0.autoWidth())
            make.height.equalToSuperview()
        }
        quanbuBt.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(60.autoWidth())
            make.left.equalToSuperview().offset(0.autoWidth())
            make.width.equalTo(itemWidth)
            make.height.equalTo(35.autoWidth())
        }
        zaixianBt.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(60.autoWidth())
            make.left.equalToSuperview().offset(itemWidth)
            make.width.equalTo(itemWidth)
            make.height.equalTo(35.autoWidth())
        }
        //        kongxianBt.snp.makeConstraints { (make) in
        //            make.top.equalToSuperview().offset(60.autoWidth())
        //            make.left.equalToSuperview().offset(itemWidth*2)
        //            make.width.equalTo(itemWidth)
        //            make.height.equalTo(35.autoWidth())
        //        }
        lixianBt.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(60.autoWidth())
            make.left.equalToSuperview().offset(itemWidth*2)
            make.width.equalTo(itemWidth)
            make.height.equalTo(35.autoWidth())
        }
        tipLine.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(93.autoWidth())
            make.centerX.equalTo(quanbuBt)
            make.width.equalTo(60.autoWidth())
            make.height.equalTo(1.5.autoWidth())
        }
    }
    
    @objc func closeBtAction(button: UIButton) {
        if let c = clickChoiceClosure {
            c(0)
            self.tf.text = ""
        }
    }
}
